package com.alingrad.iou;

import java.io.InputStream;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.QuickContactBadge;
import android.widget.TextView;

public class PeopleActivity extends ListActivity {
	private IOUDbAdapter mDb;
	
	private static final int DIALOG_ALERT_DELETE_PERSON = 0;
	
	private static final int CONTEXT_MENU_DELETE_ID = 1;
	
	private class PeopleCursorAdapter extends CursorAdapter {
		private ContentResolver mCr;
		
		public PeopleCursorAdapter(Context context, Cursor c) {
			super(context, c);
			mCr = context.getContentResolver();
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			final QuickContactBadge contactBadge = 
				(QuickContactBadge) view.findViewById(R.id.people_list_row_contact_badge);
			final TextView contactName = 
				(TextView) view.findViewById(R.id.people_list_row_name);
			final TextView balance =
				(TextView) view.findViewById(R.id.people_list_row_balance);
			
			final long personId = cursor.getLong(
					cursor.getColumnIndex(IOUDbAdapter.KEY_ID));
			float bal = cursor.getFloat(
					cursor.getColumnIndex(IOUDbAdapter.KEY_PEOPLE_BALANCE));
			final long contactId = cursor.getLong(
					cursor.getColumnIndex(IOUDbAdapter.KEY_PEOPLE_CONTACT_ID));
			
			if (contactId != -1) {
				Cursor contact = mCr.query(ContactsContract.Contacts.CONTENT_URI,
						new String[] {ContactsContract.Contacts.DISPLAY_NAME},
						ContactsContract.Contacts._ID + " = " + contactId, null, null);
				if (contact == null || contact.getCount() <= 0) {
					mDb.unlinkPerson(personId);
					contactBadge.setImageResource(R.drawable.ic_contact_picture);
					contactName.setText(cursor.getString(
							cursor.getColumnIndex(IOUDbAdapter.KEY_PEOPLE_NAME)));
				} else {
					contact.moveToFirst();
					Uri photoUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
					InputStream is = ContactsContract.Contacts.openContactPhotoInputStream(mCr, photoUri);
					
					contactBadge.assignContactUri(photoUri);
					if (is == null)
						contactBadge.setImageResource(R.drawable.ic_contact_picture);
					else
						contactBadge.setImageBitmap(BitmapFactory.decodeStream(is));
					contactName.setText(contact.getString(
							contact.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
				}
				contact.close();
			} else {
				contactBadge.setImageResource(R.drawable.ic_contact_picture);
				contactName.setText(cursor.getString(
						cursor.getColumnIndex(IOUDbAdapter.KEY_PEOPLE_NAME)));
			}
			
			balance.setTextColor(Color.GREEN);
			if (bal < 0) {
				bal *= -1;
				balance.setTextColor(Color.RED);
			}
			balance.setText("$" + bal);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			View view = null;
			
			LayoutInflater inflater = LayoutInflater.from(context);
			view = inflater.inflate(R.layout.people_list_row, parent, false);
			
			return view;
		}
		
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent i = new Intent(this, PersonActivity.class);
		final long personId = id;
		i.putExtra(PersonActivity.KEY_ID, personId);
		startActivity(i);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, CONTEXT_MENU_DELETE_ID, 0, R.string.people_context_menu_delete);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info;
		switch (item.getItemId()) {
		case CONTEXT_MENU_DELETE_ID:
			showDialog(DIALOG_ALERT_DELETE_PERSON);
			return true;
		}
		return super.onContextItemSelected(item);
	}
	
	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		switch (id) {
		case DIALOG_ALERT_DELETE_PERSON:
			AlertDialog.Builder b = new AlertDialog.Builder(this);
			b.setTitle(R.string.dialog_are_you_sure_title);
			b.setMessage(R.string.dialog_delete_person_message);
			AlertDialog d = b.create();
			OnClickListener onClickListener = new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if (which == AlertDialog.BUTTON_POSITIVE) {
//						onDeleteButtonPressed(personId);
					}
					else if (which == AlertDialog.BUTTON_NEGATIVE)
						dialog.dismiss();
				}
			};
			d.setButton(AlertDialog.BUTTON_POSITIVE, getResources().getString(R.string.okay), onClickListener);
			d.setButton(AlertDialog.BUTTON_NEGATIVE, getResources().getString(R.string.cancel), onClickListener);
			return d;
		}
		return super.onCreateDialog(id);
	}

	private void onDeleteButtonPressed(long personId) {
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.people);
		mDb = new IOUDbAdapter(this);
		registerForContextMenu(getListView());
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		mDb.open();
		fillData();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		mDb.close();
	}
	
	private void fillData() {
		Cursor c = mDb.getPeople();
		startManagingCursor(c);
		setListAdapter(new PeopleCursorAdapter(this, c));
	}
}
